package com.ctrip.ec.api.mobile.controller;


import com.ctrip.ec.api.mobile.aop.AuthLogin;
import com.ctrip.ec.api.mobile.common.RequestContext;
import com.ctrip.ec.api.mobile.common.ValidateException;

import com.ctrip.ec.biz.dao.member.MemberAddressDao;
import com.ctrip.ec.biz.entity.member.MemberAddressEntity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.List;

@RestController
@RequestMapping("memberAddress")
@AuthLogin
public class MemberAddressController {
    @Autowired
    private MemberAddressDao memberAddress;

    @GetMapping("list")
    @AuthLogin
    public List<MemberAddressEntity> list() throws SQLException {
        String where = "member_id =" + RequestContext.getMemberId();
        List<MemberAddressEntity> list = memberAddress.list(where);
        return list;
    }

    @GetMapping("detail/{id}")
    @AuthLogin
    public MemberAddressEntity detail(@PathVariable(required = false) Long id) throws SQLException {
        MemberAddressEntity entity = null;
        if(id == null || id == 0){
            entity = memberAddress.entityByDefault(RequestContext.getMemberId());
        }else {
            entity = memberAddress.entity(id);
            if(entity != null) {
                if (!entity.getMemberId().equals(RequestContext.getMemberId())) {
                    throw new ValidateException("无权访问别人的送货地址");

                }
            }
        }
        return entity;
    }



    @PostMapping("save")
    @AuthLogin
    public Long save(@RequestBody MemberAddressEntity entity) throws SQLException {

        if(entity.getIsDefault() == true){
            memberAddress.clearDefault(RequestContext.getMemberId());
        }
        entity.setMemberId(RequestContext.getMemberId());
        if(memberAddress.getAddressCount(RequestContext.getMemberId()) == 0){
            entity.setIsDefault(true);
        }
        memberAddress.save(entity);
        return entity.getId();
    }

    @PostMapping("delete")
    @AuthLogin
    public void delete(@RequestBody List<Long> ids) throws SQLException {
        if(ids != null && ids.size()>0) {
            List<MemberAddressEntity> list = memberAddress.listByIds(ids);
            for (MemberAddressEntity entity : list) {
                if (!entity.getMemberId().equals(RequestContext.getMemberId())) {
                    throw new ValidateException("无权删除别人的送货地址");
                }
            }
            memberAddress.delete(ids);
        }
    }

}
